package com.bgs.interceptor;

import com.bgs.annotation.NoneAuth;
import com.bgs.utils.NormalConstant;
import com.bgs.utils.TokenHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: D.c_h
 * @create: 2021-07-08 21:28
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenHelper tokenHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法，放行
        if(!(handler instanceof HandlerMethod)) return true;
        // 如果被@NoneAuth注解代表不需要登录验证，直接通过
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(method.getAnnotation(NoneAuth.class) != null) return true;
        // token—check
        String authStr = request.getHeader(NormalConstant.AUTHORIZATION);
        boolean b = tokenHelper.check(authStr);
        if (b) {
            return true;
        }
        // 验证未通过
        request.getRequestDispatcher("/err/acl").forward(request, response);
        return true;
    }
}
